#include "filehandler.h"

#include <QtSql>
#include <QFile>
#include <QDebug>

FileHandler::FileHandler()
{
}

/*
  This is purely a convenience method, used for reading
  a .sql file
 */
QString FileHandler::readTextFile(QString path)
{
    QFile file(path);
    QByteArray byteContents;

    if (!file.exists()) {
        return "";
    }

    file.open(QFile::ReadOnly);
    byteContents = file.readAll();
    file.close();

    QString strContents(byteContents);
    return strContents;
}

/*
  Initializes an empty SQLite database.
 */
void FileHandler::initializeDatabase()
{
    QSqlDatabase db = QSqlDatabase::database();
    QSqlQuery query(db);
    bool success = true;
    bool hasFailure = false;
    int i;
    QString filePaths[] = {"res/supplier.sql", "res/customer.sql",
                       "res/item.sql", "res/transaction.sql",
                       "res/stock.sql", "res/metadata.sql"};

    for (i = 0; i < 5; i++) {
        success = query.exec(readTextFile(filePaths[i]));
        if (!success) {
            hasFailure = true; // oh noes delayed ako
            qDebug() << "FileHandler: Failure reason: " << query.lastError().text();
        }
    }

    if (hasFailure) {
        qDebug() << "FileHandler: Failed to initialize SQLite database!";
    }
}

/*
  Opens the SQLite database file at the specified filesystem path.
 */
bool FileHandler::openFileAt(QString path, OpenAction action)
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    QFile file(path);
    bool ok;

    if (action == InitDatabase && file.exists()) {
        qDebug() << "FileHandler: Deleting " << path;
        bool success = QFile::remove(path);
        if (!success) {
            qDebug() << "FileHandler: Deletion failed!";
        }
    }

    db.setDatabaseName(path);
    ok = db.open();

    if (!ok) {
        qDebug() << "FileHandler: Failed to open SQLite database file! " << path;
    }

    if (ok && action == InitDatabase) {
        initializeDatabase();
    }

    return ok;
}

/**
  Close the database
  */
void FileHandler::closeFile()
{
    QSqlDatabase::database().close();
}
